﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Net;
using System.IO;

namespace SmsApi
{
    public class SmsClient
    {
        /// <summary>
        /// Nazwa użytkownika w serwisie SMSAPI
        /// </summary>
        private string username;

        public string Username
        {
            get { return username; }
            set { username = value; }
        }

        /// <summary>
        /// Hasło do Twojego konta w serwisie SMSAPI zaszyfrowane w MD5
        /// </summary>
        private string password;

        public string Password
        {
            get { return password; }
            set { password = value; }
        }

        //private string url = @"http://api.smsapi.pl/sms.do";
        //private string urlbackup = @"http://api2.smsapi.pl/sms.do";
        private string url;

        public string Url
        {
            get { return url; }
            set { url = value; }
        }

        public SmsClient(string user, string pass,string ur)
        {
            this.username = user;
            this.password = pass;
            this.url = ur;
        }

        
        public SmsClient() : this("", "","") { }

        /*
         http://api.smsapi.pl/sms.do?username=uzytkownik&password=hasloMD5&from=nazwa
         * &to=48500500500,48501501501,48502502502&message=test wiadomosc
         * */
        public List<SmsResponse> send(SmsMessage msg)
        {
            // Tworzenie queryStringa
            NameValueCollection parametry = initialize(msg);
            //string querystring = queryString(parametry);

            WebClient webClient = new WebClient();
            if (!string.IsNullOrEmpty(url))
            {
                byte[] response = webClient.UploadValues(url, "POST", parametry);
                return analyzeResonse(response);
            }
            else
                return null;
    
        }

        public SmsResponse amountOfPoints(SmsMessage msg)
        {
            NameValueCollection parametry = initialize(msg);
            WebClient webClient = new WebClient();
            SmsResponse sr = new SmsResponse();
            if (!string.IsNullOrEmpty(url))
            {
                byte[] response = webClient.UploadValues(url, "POST", parametry);


                string responsestr = Encoding.ASCII.GetString(response);

                string[] tab1 = responsestr.Split(':');
                string[] tab2 = tab1[1].Split(';');
                
                
                sr.Status = tab1[0];
                if (tab2.Length >= 3)
                {
                    sr.Pkt = tab2[0];
                    sr.Pro = tab2[1];
                    sr.Eco = tab2[2];
                }
            }
            return sr;
        }

        public List<SmsResponse> analyzeResonse(byte[] resp)
        {
            string response = Encoding.ASCII.GetString(resp);
            //Console.WriteLine(response);
            List<SmsResponse> listResponse = new List<SmsResponse>();
            SmsResponse sr = new SmsResponse();

            string[] detailsResponse = response.Split('\n');
            string[] split;
            if (detailsResponse.Length > 1)
            {
                
               detailsResponse[0] = detailsResponse[0].Remove(0, detailsResponse[0].IndexOf(':')+2);
               detailsResponse[1] = detailsResponse[1].Remove(0, detailsResponse[1].IndexOf(':')+2);
               detailsResponse[2] = detailsResponse[2].Remove(0, detailsResponse[2].IndexOf(':')+2);
               detailsResponse[3] = detailsResponse[3].Remove(0, detailsResponse[3].IndexOf(':')+2);

                split = detailsResponse[4].Split(';');

            }
            else
                split = response.Split(';');



            foreach (string str in split)
            {
                sr = new SmsResponse();
                string[] tmp = str.Split(':');
                if (tmp.Length == 2)
                {
                    sr.Status = tmp[0];
                    sr.Err = tmp[1];
                }
                else if (tmp.Length == 3)
                {
                    sr.Status = tmp[0];
                    sr.Id = tmp[1];
                    sr.Points = tmp[2];
                }
                else if(tmp.Length == 4)
                {
                    sr.Status = tmp[0];
                    sr.Id = tmp[1];
                    sr.Points = tmp[2];
                    sr.Phone = tmp[3];
                }
                if (detailsResponse.Length == 4)
                {
                    sr.Message = detailsResponse[0];
                    sr.Length = detailsResponse[1];
                    sr.Smscount = detailsResponse[2];
                    sr.Parts = detailsResponse[3];
                }

                listResponse.Add(sr);                
            }

            return listResponse;
        }

        //void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        //{
        //    if (e.Error == null)
        //    {
        //        Stream stream = e.Result;
        //        StreamReader sr = new StreamReader(stream);
        //        string response = sr.ReadToEnd();
        //        Console.WriteLine(response);
        //    }
        //}
        private NameValueCollection initialize(SmsMessage msg)
        {
            NameValueCollection parametry = new NameValueCollection();
            //Dodawanie adresu
          //  parametry.Add("url", url);
            //Dodawanie usera i passowrd
            parametry.Add("username", this.username);
            parametry.Add("password", this.Password);

            // Sprawdzanie czy podano nadawce
            if (!string.IsNullOrEmpty(msg.From))
            {
                parametry.Add("from", msg.From);
            }

            // Grupy
            if (!string.IsNullOrEmpty(msg.Group))
            {
                parametry.Add("group", msg.Group);
            }
            else if(msg.To.Count>0)
            {
                foreach (SmsAddress adres in msg.To)
                {
                    parametry.Add("to", adres.PhoneNumber);
                }
            }

            // Wiadomosc
            if(!string.IsNullOrEmpty(msg.Message))
                parametry.Add("message", msg.Message);

            // Eco
            if (msg.Eco != 0)
                parametry.Add("eco", msg.Eco.ToString());

            // Nounicode
            if (msg.Nounicode != 0)
                parametry.Add("nounicode", msg.Nounicode.ToString());

            // Fast
            if (msg.Fast != 0)
                parametry.Add("fast", msg.Fast.ToString());

            // Flash
            if (msg.Flash != 0)
                parametry.Add("flash", msg.Flash.ToString());

            // Test
            if (msg.Test != 0)
                parametry.Add("test", msg.Test.ToString());

            // Details
            if (msg.Details != 0)
                parametry.Add("details", msg.Details.ToString());

            // Date
            if (msg.Date != 0)
                parametry.Add("date", msg.Date.ToString());

            // Idx
            if (msg.Idx != 0)
                parametry.Add("idx", msg.Idx.ToString());

            // Points
            if (msg.Points != 0)
                parametry.Add("points", msg.Points.ToString());

            
            return parametry;
        }

        private string queryString(NameValueCollection parametry){

            string query = String.Empty;


            foreach (String param in parametry.Keys)
            {
                if (param.Equals("url"))
                {
                    query += parametry[param];
                }
                else
                    if (!query.Contains("?"))
                    {
                        query += String.Format("?{0}={1}", param, parametry[param]);
                    }
                    else
                    {
                        query += String.Format("&{0}={1}", param, parametry[param]);
                    }               
            }
            return query;
        }

       
       
    }
}
